package com.luli.controllor;

import com.luli.Utils.FileUtil;
import com.luli.Utils.HtmlParseUtils;
import com.luli.Utils.LocaleMessageSourceUtil;
import com.luli.dao.UsersDao;
import com.luli.entity.Blood;
import com.luli.entity.response.ResponseMsg;
import com.luli.service.IElasticSearchService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.rest.RestStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import static com.luli.Utils.ResponseMsgUtil.getFailMsg;
import static com.luli.Utils.ResponseMsgUtil.getSuccessMsg;
import static com.luli.constant.EsConstant.EN_US;

/**
 * 陆离
 * 2022/5/3 20:31:35
 */
@RestController
@Slf4j
@RequestMapping("/JD")
@CrossOrigin
public class ElasticsearchController {

    @Autowired
    private IElasticSearchService elasticSearchService;
    @Autowired
    private MessageSource messageSource;
    @Autowired
    private LocaleMessageSourceUtil messageSourceUtil;
    @Autowired
    private UsersDao usersDao;

    @GetMapping("/selAllData")
    public List<Map<String, Object>> getDataAll() throws IOException {
        List<Map<String, Object>> maps = elasticSearchService.selAllData();
        return maps;
    }

    @GetMapping("/getSearchDown")
    public List<Map<String, Object>> getSearchDown() throws IOException {
        List<Map<String, Object>> searchDown = HtmlParseUtils.getSearchDown("java");
        log.info("searchDown",searchDown);
        return searchDown;
    }

    /**
     * 新建索引
     * @param keyWord
     * @return
     * @throws IOException
     */
    @GetMapping("/parse/{keyWord}")
    public Boolean getData(@PathVariable("keyWord") String keyWord) throws IOException {
        return elasticSearchService.searchKeyword(keyWord);
    }

    /**
     * 页面搜索
     * @param keyword
     * @param pageNo
     * @param pageSize
     * @return
     * @throws IOException
     */
    @GetMapping("/search/{keyword}/{pageNo}/{pageSize}")
    public List<Map<String, Object>> search(@PathVariable("keyword") String keyword, @PathVariable("pageNo")int pageNo, @PathVariable("pageSize")int pageSize) throws IOException {
        return elasticSearchService.searchPage(keyword, pageNo, pageSize);
    }

    /**
     * 高亮
     * @param keyword
     * @param pageNo
     * @param pageSize
     * @return
     * @throws IOException
     */
    @GetMapping("/searchHighlight/{keyword}/{pageNo}/{pageSize}")
    public List<Map<String, Object>> searchHighlight(@PathVariable("keyword") String keyword, @PathVariable("pageNo")int pageNo, @PathVariable("pageSize")int pageSize) throws IOException {
        return elasticSearchService.searchHighlight(keyword,pageNo,pageSize);
    }

    /**
     * 根据id删除ES中的数据
     * @param id
     * @return
     */
    @RequestMapping(value = "/deleteGood" , method = RequestMethod.DELETE)
    public RestStatus deleteGood(String id){
        RestStatus restStatus = null;
        try {
            restStatus = elasticSearchService.deleteGood(id);
        } catch (IOException ioException) {
            log.error("删除失败",restStatus);
        }
        return restStatus;

    }
    @RequestMapping(value = "/title" , method = RequestMethod.GET)
    public String deleteGood(){
        String title = messageSource.getMessage("hello", null, LocaleContextHolder.getLocale());
        return title;
    }


    @GetMapping("test")
    public String test() {
        // 获取客户端的语言环境Locale对象，即取的请求头Accept-Language键的值来判断，我们也可以自定义请求头键，来获取语言标识
        Locale locale = LocaleContextHolder.getLocale();
        String userName = messageSource.getMessage("userName", null, locale);
        System.out.println(userName);
        return userName;
    }


    /**
     * 发请求需要将  headers 设置为 accept=application/json;charset=utf-8
     * @return
     */
    @RequestMapping("/i18n")
    public String hello() {
        String welcome = messageSourceUtil.getMessage("userName",null,null,EN_US);
        return welcome;
    }
    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

    @RequestMapping(value = "/addMap" , method = RequestMethod.POST)
    public ResponseMsg<?> addSettingAndMapping(String mappingName,String indexName) throws IOException {
        //统一处理为小写
        String indexNameLower = indexName.toLowerCase();
        if (ObjectUtils.isEmpty(mappingName) || ObjectUtils.isEmpty(indexNameLower)) {
            return getFailMsg(null, "mappingName或者indexName不能为空", null);
        }else {
            GetIndexRequest isIndexName = new GetIndexRequest(indexNameLower);
            boolean exists = client.indices().exists(isIndexName, RequestOptions.DEFAULT);
            if (!exists) {
                CreateIndexRequest request = new CreateIndexRequest(indexNameLower);
                request.source(mappingName, XContentType.JSON);
                CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
                System.out.println(createIndexResponse.isAcknowledged());
                return getSuccessMsg(null, String.valueOf(createIndexResponse.isAcknowledged()), null);
            }else {
                return getFailMsg(null, "索引已经存在", null);
            }
        }
    }


    @GetMapping("/testLink")
    public List<Blood> getTestLink() throws IOException {
        List<Blood> bloodData = usersDao.getBloodData();
        return bloodData;
    }

    /**
     * 文件上传json
     * @param fileName
     * @return
     * @throws IOException
     */
    @GetMapping("/testFile")
    public Boolean getTestLinks2(File fileName) throws IOException {
        Boolean aBoolean = elasticSearchService.uploadingText(fileName);
        return aBoolean;
    }

    @GetMapping("/testFile2")
    public Boolean testFile2(File file) throws IOException {
        Boolean aBoolean = elasticSearchService.fileUploading(file);
        return aBoolean;
    }



}
